package com.songxh.core.utils;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.DownloadUrl;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


/**
 * 七牛云的图片上传工具类
 *
 * @author songxh
 * @create 2023-01-16-10:17
 */
@Slf4j
@Component
public class QINIUUploadFileUtils {
    //AK
    @Value("${file.io.accessKey}")
    private String ACCESS_KEY;

    //SK
    @Value("${file.io.secretKey}")
    private String SECRET_KEY;

    //空间名称
    @Value("${file.io.bucketName}")
    private String BUCKET_NAME;

    //图片的上传路径
    @Value("${file.io.url}")
    private String URL;

    /**
     * 生成上传token
     *
     * @return
     */
    public String getUpToken() {
        return Auth.create(ACCESS_KEY, SECRET_KEY).uploadToken(BUCKET_NAME, null, 3600, new StringMap().put("insertOnly", 1));
    }

    /**
     * 上传文件
     *
     * @param file
     * @param fileName
     * @return
     */
    public String uploadFile(MultipartFile file, String fileName) {
        //根据存储区域来配置（华南）
        Configuration configuration = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(configuration);
        try {
            byte[] uploadBytes = file.getBytes();
            Response response = uploadManager.put(uploadBytes, fileName, getUpToken());
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            log.info("上传文件响应内容：{}", putRet.toString());
            //七牛云中存入的文件名
            String name = putRet.key;
            return name;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 图片回显， 传回一个url
     *
     * @param imageName
     * @return
     */
    public String download(String imageName) throws QiniuException {
        //imageName：在七牛云中的名称,   外链域名 + 图片名
        DownloadUrl downloadUrl = new DownloadUrl(URL, false, imageName);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        //设置过期时间
        long expire = 1000 * 3600 * 24 * 7;//过期时间为一周
        long deadTime = System.currentTimeMillis() + expire;
        String url = downloadUrl.buildURL(auth, deadTime);
        return url;
    }

}
